import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";

Vue.use(VueRouter);

const routes: Array<RouteConfig> = [
  {
    meta: {
      isAuth: false,
      isManager: false,
    },
    path: "/",
    name: "Index",
    component: () => import("../views/Index/Index.vue"),
  },
  {
    meta: {
      isAuth: false,
      isManager: false,
    },
    path: "/create-order",
    name: "Save",
    component: () => import("../views/save-order/save-order.vue"),
  },
  {
    meta: {
      isAuth: false,
      isManager: false,
    },
    path: "/customer-login",
    name: "CustomerLogin",
    component: () => import("../views/customer/login.vue"),
  },
  {
    meta: {
      isAuth: true,
      isManager: false,
    },
    path: "/customer-index",
    name: "CustomerIndex",
    component: () => import("../views/customer/index.vue"),
  },
  {
    meta: {
      isAuth: false,
      isManager: false,
    },
    path: "/login",
    name: "ManagerLogin",
    component: () => import("../views/login/login.vue"),
  },
  {
    meta: {
      isAuth: true,
      isManager: true,
    },
    path: "/manager-index",
    name: "ManagerIndex",
    component: () => import("../views/manager/index.vue"),
  },
  {
    meta: {
      isAuth: true,
      isManager: true,
    },
    path: "/order-info",
    name: "OrderInfo",
    component: () => import("../views/manager/components/order-info.vue"),
  },
  {
    meta: {
      isAuth: true,
      isManager: true,
    },
    path: "/counter-info",
    name: "CounterInfo",
    component: () => import("../views/manager/components/counter-info.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
router.beforeEach((to, from, next) => {
  // 管理员验证
  const managerAuth =
    (to.meta as any).isManager &&
    (to.meta as any).isAuth &&
    !localStorage.getItem("manager-token");
  // 客户验证
  const customerAuth =
    !(to.meta as any).isManager &&
    (to.meta as any).isAuth &&
    !localStorage.getItem("customer-token");
  if (managerAuth) {
    next("/login");
  } else if (customerAuth) {
    next("/customer-login");
  }
  next();
});

export default router;
